package edu.zut.cs.software.example.Student.web.spring.controller;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

import edu.zut.cs.software.example.QueryInfo.QueryInfo;
import edu.zut.cs.software.example.student.domain.Student;
import edu.zut.cs.software.example.student.service.StudentManager;
import edu.zut.cs.software.example.util.JWT.JwtHelper;
/**
 * 
 * @author chen ming yang
 *
 */
@RestController
public class StudentController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LogManager.getLogger(StudentController.class.getName());

	
	@Autowired
	StudentManager studentManager;
	
	@RequestMapping("/getNewInfo")
	public String getNewInfo(HttpServletRequest request) {
		String ACtoken = request.getHeader("Authorization");
		String userId =JwtHelper.parseAndget(ACtoken);
		Student student =studentManager.getStudent(userId);
//		System.out.println(student);
		HashMap<String,Object> res=new HashMap<>();
		res.put("student",student);
		return JSON.toJSONString(res);
	}

	/**
	 *  在不指定name值的情况下默认查询获取同班级用户（学生）的所有信息
	 * @param  queryInfo
	 * @return res_string
	 */
	@RequestMapping("/getByClas")
	public String getStudentList(QueryInfo queryInfo) {
		HashMap<String,Object> res=studentManager.getClassmatesService(queryInfo);
		return JSON.toJSONString(res);
	}

	/**
	 * 通过指定id查询用户信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/getupdate")
	public String getUpdateStudent(int id) {
		return JSON.toJSONString(studentManager.getUpdateStuService(id));
	}
	
	/**
	 * 编辑修改个人资料
	 * @param VueStudent
	 * @return
	 */
	@RequestMapping("/editInfo")
	public String editStudentInfo(@RequestBody Student student) {
		String flag="error";
		System.out.println(student);
		int resCode=studentManager.editStuInfoService(student);
		
		if(resCode==1) flag="success";
		
		HashMap<String,Object> res=new HashMap<String, Object>();
		res.put("flag", flag);
		
		int id=Integer.parseInt(String.valueOf(student.getId()));
		
		Student newStuInfo=studentManager.getUpdateStuService(id);
		
		res.put("student", newStuInfo);
		
		String r =  JSON.toJSONString(res);

		return r;
	}

	@RequestMapping("/getUserInfo")
	public String getUserInfo(HttpServletRequest request) {
		String ACtoken = request.getHeader("Authorization");
		String userId= JwtHelper.parseAndget(ACtoken);
		
		HashMap<String,Object> res=studentManager.getUserInfo(userId);

		
		String r =  JSON.toJSONString(res);
		
		return r;
		
	}

}
